/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.security.config

import com.gitee.minimalismstyle.fresh.common.core.const.CacheConst
import com.gitee.minimalismstyle.fresh.common.core.extra.log
import com.gitee.minimalismstyle.fresh.common.core.service.ResourceService
import com.gitee.minimalismstyle.fresh.common.security.intercept.DynamicFilterSecurityInterceptor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.context.WebServerInitializedEvent
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.event.EventListener
import org.springframework.data.redis.connection.Message
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.listener.ChannelTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.access.SecurityConfig
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
import java.util.LinkedHashMap
import kotlin.streams.toList

/**
 * 动态权限配置
 * @author maoxiaodong
 */
@Configuration
class FreshDynamicSecurityConfig(val redisTemplate: StringRedisTemplate,
                                 val dynamicFilterSecurityInterceptor: DynamicFilterSecurityInterceptor) {

    @Value("\${spring.application.name}")
    var serviceId: String = ""

    @Autowired
    lateinit var resourceService: ResourceService

    //@Bean
    fun securityRedisContainer(): RedisMessageListenerContainer {
        val container = RedisMessageListenerContainer()
        redisTemplate.connectionFactory?.let { container.setConnectionFactory(it) }
        container.addMessageListener( { _: Message?, _: ByteArray? ->
            log.warn("重新加载资源权限事件")
            loadSecurityMetadata()
        }, ChannelTopic(CacheConst.RESOURCES_RELOAD_TOPIC))
        return container
    }

    /**
     * 加载资源权限
     */
    @EventListener(WebServerInitializedEvent::class)
    fun loadSecurityMetadata() {
        dynamicFilterSecurityInterceptor.securityMetadataSource =
                ExpressionBasedFilterInvocationSecurityMetadataSource(getRequestMatcher(), OAuth2WebSecurityExpressionHandler())
    }

    fun getRequestMatcher(): LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> {
        val resources = resourceService.getResourceByServiceId(serviceId).get(listOf())
        val requestMap: LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> = linkedMapOf()
        if (resources.isNotEmpty()) {
            resources.forEach { resource ->
                val matcher = if (resource.httpMethod == null
                        || resource.httpMethod == "") {
                    AntPathRequestMatcher(resource.link)
                } else {
                    AntPathRequestMatcher(resource.link, resource.httpMethod)
                }

                val configs: MutableList<ConfigAttribute> = if (resource.roleList != null && resource.roleList!!.isNotEmpty()) {
                    val hasRoles = resource.roleList!!.stream().map { "hasRole('ROLE_$it')" }
                            .toList().toTypedArray()
                    SecurityConfig.createList(*hasRoles)
                } else {
                    SecurityConfig.createList("permitAll")
                }

                requestMap[matcher] = configs
            }
        }
        requestMap[AntPathRequestMatcher("/token/**")] = SecurityConfig.createList("permitAll")
        requestMap[AnyRequestMatcher.INSTANCE] = SecurityConfig.createList("authenticated")
        return requestMap
    }

}